<template>
  <a-modal
    :open="open"
    width="1200px"
    :title="rowData.txm ? '修改检验申请单' : '新增检验申请单'"
    centered
    :keyboard="false"
    :ok-button-props="{ disabled: !isCompleted }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="w-[550px]" :colon="false" :label-col="{ style: { width: '78px' } }">
      <a-form-item label="姓名" name="brName" v-bind="validateInfos.brName">
        <SelectTable
          v-if="rowData.apply === 0"
          v-model:value="formState.brName"
          type="检验患者"
          :search-params="{ stdate: dayjs().format('YYYY-MM-DD'), eddate: dayjs().format('YYYY-MM-DD') }"
          @select="(row) => onSelect(row, 1)"
        />
        <SelectTable v-else v-model:value="formState.brName" type="押金检索收取押金" @select="(row) => onSelect(row, 1)" />
      </a-form-item>
    </a-form>
    <div style="margin-left: 76px">
      <div class="card-box flex flex-wrap justify-between">
        <a-card class="card-item active" :body-style="{ padding: 0 }" hoverable>
          <div class="item-header">
            <a-avatar class="ml-2" :src="avatarMan" />
            <div class="flex-1 ml-5 flex justify-between items-center">
              <div class="font-semibold">
                {{ userData?.brName || '-' }}
              </div>
              <div class="">
                {{ userData?.brXb || '-' }}
              </div>
              <div class="">{{ userData?.brAge || '-' }}</div>
              <a-divider type="vertical" class="!border-white" />

              <div class="">
                {{ userData?.brMob || '-' }}
              </div>
              <div class="" style="min-width: 80px">
                <span>{{ userData?.brId || '-' }}</span>
              </div>
              <template v-if="rowData.apply === '1'">
                <LabelValue class="" label="病区" :width="160" :value="userData?.wardName" />
                <LabelValue class="" label="床位号" :width="160" :value="userData?.bedCode" />
              </template>
            </div>
          </div>
          <slot></slot>
        </a-card>
      </div>
    </div>
    <div class="flex mt-4">
      <div class="w-[520px]" style="margin-left: 76px">
        <BaseTable
          column-code="000228"
          :data-source="tableData"
          :custom-row="onClickRow"
          :row-class-name="(record) => (record.categroyCode === categroyCode ? 'selected-row' : '')"
          :scroll="{ x: 400, y: 520 }"
          :height="530"
          :loading="loading"
        >
          <template #bodyCell="{ column, index }">
            <template v-if="column.dataIndex == 'xh'">
              {{ index + 1 }}
            </template>
          </template>
        </BaseTable>
      </div>
      <div class="w-[540px] ml-4">
        <BaseTable
          column-code="000229"
          row-key="id"
          :data-source="projectData"
          :scroll="{ x: 400, y: 520 }"
          :height="530"
          :loading="loadingProject"
          :row-selection="rowSelection"
        />
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import SelectTable from '@/components/SelectTable'
import { post } from '@/utils/request'
import useAppStore from '@/store/user'
import avatarMan from '@/assets/images/avatar-man.png'

const storeUser = useAppStore()
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({ brName: '' })
const userData = ref({})
const categroyCode = ref('')
const categroyRow = ref({})
const selectedRowKeys = ref([])
const selectedRows = ref([])
const emit = defineEmits(['update:open', 'success'])
const rulesState = ref({
  brName: [{ required: true, message: '请选择' }]
  // applyDoctorId: [{ required: true, message: '请选择' }]
})
const { isCompleted, validateInfos } = useForm(formState, rulesState)

const { loading, getData, tableData } = useTable({
  url: '/lis/InstrumentType/getLisCategroyList',
  formatResult: (data) => {
    categroyCode.value = formState.value.categroyCode || data[0]?.categroyCode
    categroyRow.value = data ? data[0] : {}
    selectedRowKeys.value = []
    selectedRows.value = []
    getProjectData()
    return data
  }
})

const {
  loading: loadingProject,
  getData: getProjectData,
  tableData: projectData
} = useTable({
  url: '/lis/LisApply/getlisInstrumentTypeRelationByCategroyCodeList',
  formatParams: () => {
    return {
      categroyCode: categroyCode.value,
      lsh: formState.value.lsh
    }
  },
  formatResult: (data) => {
    const arr = data.map((item) => {
      return {
        ...item,
        id: item.lisSetId || item.orderItemCode,
        type: item.lisSetId ? '组套' : '项目'
      }
    })
    // selectedRowKeys.value = arr.map((item) => item.id)
    // selectedRows.value = arr
    return arr
  }
})

const rowSelection = ref({
  checkStrictly: true,
  selectedRowKeys: selectedRowKeys,
  onChange: (keys, rows) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  }
})

const onSelect = (row, state) => {
  if (state === 1) {
    userData.value = row
    formState.value.brName = row.brName
    formState.value.brId = row.brId
    formState.value.key = row.jzbh || row.inplsh
    formState.value.bcLczdZddm = row.bcLczdZddm ?? row.icd10Code
    formState.value.applyDeptCode = row.ksdm ?? row.lastDeptCode
  } else {
    formState.value.applyDoctorName = row.empName
    formState.value.applyDoctorId = row.empId
    formState.value.applyDeptName = row.ksmc
    formState.value.applyDeptCode = row.lastDeptCode
  }
}

const onClickRow = (record) => {
  return {
    onClick: () => {
      categroyCode.value = record.categroyCode
      categroyRow.value = record
      selectedRowKeys.value = []
      selectedRows.value = []
      getProjectData()
    }
  }
}

const onOk = async () => {
  if (selectedRowKeys.value.length === 0) return message.error('请选择项目')

  const orderItemCodeList = []
  const lisSetIdList = []
  selectedRows.value.forEach((item) => {
    if (item.type === '组套') {
      lisSetIdList.push(item.id)
    } else {
      orderItemCodeList.push(item.id)
    }
  })
  const { code, msg } = await post('/lis/LisApply/doSaveLisApply', {
    ...categroyRow.value,
    ...formState.value,
    brId: formState.value.brId,
    orderItemCodeList,
    lisSetIdList,
    applyPath: props.rowData?.apply,
    applyDoctorId: storeUser.empId,
    key: formState.value?.key
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  onReset()
  emit('update:open', false)
  emit('success')
}

const onReset = () => {
  formState.value = {}
  userData.value = {}
}

const onCancel = () => {
  onReset()
  emit('update:open', false)
}
watch(
  () => props.open,
  async (val) => {
    if (val) {
      formState.value = { ...props.rowData }
      await getData()
      userData.value = { ...props.rowData }
      categroyCode.value = props.rowData.categroyCode || categroyCode.value
    }
  }
)
</script>
<style lang="less" scoped>
.card-box {
  overflow: hidden auto;
  .card-item {
    width: 100%;
    height: fit-content;
    &.active {
      border: 1px solid var(--primary-color);
      .item-header {
        color: #fff;
        background-color: var(--primary-color);
        .font-semibold {
          font-size: 18px;
        }
      }
    }
    .item-header {
      position: relative;
      display: flex;
      padding: 8px;
      background-color: #00000010;
    }
  }
}
</style>
